﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

internal class UDP_Network
{

    public async Task ReceiveAsync(string ip,int listenPort)
    {
        //创建一个udp通信类
        UdpClient receiver = new UdpClient(new IPEndPoint(IPAddress.Parse(ip), listenPort));
        try
        {
            while (true)
            {
                // 接收数据
                UdpReceiveResult receiveBytes = await receiver.ReceiveAsync();
                //数据转换
                string receiveMessage = Encoding.ASCII.GetString(receiveBytes.Buffer);
                EventHub.RequestTab(receiveMessage);
            }
        }
        catch (Exception e)
        {
            MessageBox.Show($"Error: {e}");
        }
        finally
        {
            receiver.Close();
        }

    }

    public async Task ServerSendAsync(string ip,int targetPort, string message)
    {
        UdpClient sender = new UdpClient();
        IPEndPoint targetEndPoint = new IPEndPoint(IPAddress.Parse(ip), targetPort);
        try
        {
            //数据转换
            byte[] sendBytes = Encoding.ASCII.GetBytes(message);
            // 发送数据
            await sender.SendAsync(sendBytes, sendBytes.Length, targetEndPoint);
        }
        catch (Exception e)
        {
            MessageBox.Show($"Error: {e}");
        }
        finally
        {
            sender.Close();
        }
    }

    public void Receive(string ip,int port)
    {
        IPEndPoint iPEnd = new IPEndPoint(IPAddress.Parse(ip), port);
        UdpClient receiver = new UdpClient(iPEnd);
        while (true) 
        {
            byte[] recebyte = receiver.Receive(ref iPEnd);
            string receiveMessage = Encoding.ASCII.GetString(recebyte);
            EventHub.RequestTab(receiveMessage);
        }
    }

    public void ServerSend(string ip, int targetPort, string message)
    {
        IPEndPoint iPEnd = new IPEndPoint(IPAddress.Parse(ip), targetPort);
        UdpClient receiver = new UdpClient(iPEnd);
        byte[] sendBytes = Encoding.ASCII.GetBytes(message);
        receiver.Send(sendBytes);
    }
}
